package com.stox.shared.indicator.model;

import com.stox.shared.indicator.model.config.BaseIndicatorConfig;
import com.stox.shared.indicator.model.config.StochasticConfig;
import com.stox.shared.indicator.model.enumeration.IndicatorDisplayType;
import com.stox.shared.indicator.model.enumeration.IndicatorPosition;

public class Stochastic extends AbstractIndicator<StochasticValue, StochasticConfig>{

	public static final Stochastic INSTANCE = new Stochastic();
	
	private Stochastic() {
		super("STO");
	}
	
	@Override
	public IndicatorPosition getPosition(StochasticConfig config) {
		return IndicatorPosition.INDEPENDENT;
	}

	@Override
	public IndicatorDisplayType getDisplayType(StochasticConfig config) {
		return IndicatorDisplayType.DUAL_LINE;
	}

	@Override
	public StochasticValue getValue(StochasticConfig configuration, Double[] in, int index) throws UnsupportedOperationException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public StochasticValue[] getValues(StochasticConfig configuration, Double[] in) throws UnsupportedOperationException {
		BaseIndicatorConfig baseIndicatorConfig = new BaseIndicatorConfig();
		baseIndicatorConfig.setBarValue(configuration.getBarValue());
		baseIndicatorConfig.setSpan(configuration.getSlowSpan());
		Double[] sma = SimpleMovingAverage.INSTANCE.getValues(baseIndicatorConfig, in);
		int span = configuration.getSpan();
		int dSpan = configuration.getdSpan();
		StochasticValue[] result = new StochasticValue[in.length];
		for(int index = in.length - span - 1; index >= 0; index--){
			double max = Double.MIN_VALUE;
			double min = Double.MAX_VALUE;
			for(int index2 = index; index2 < index + span; index2++){
				Double value = sma[index2];
				if(null != value){
					max = Math.max(max, sma[index2]);
					min = Math.min(min, sma[index2]);
				}
			}
			Double k = (sma[index]-min)*100/(max-min);
			Double d = null;
			if(index < in.length - span - dSpan){
				double sum = k;
				for(int index2 = index+1; index2 < index + dSpan; index2++){
					StochasticValue value = result[index2];
					if(null != value){
						sum += value.getK();
					}
				}
				d = sum/dSpan;
			}
			result[index] = new StochasticValue(k, d);
		}
		return result;
	}

	@Override
	public StochasticConfig createDefaultConfiguration() {
		return new StochasticConfig();
	}

}
